package com.caine.threadpool;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.*;

public class ForkJoinTest {

    private static ForkJoinPool.ForkJoinWorkerThreadFactory factory = new ForkJoinPool.ForkJoinWorkerThreadFactory() {
        @Override
        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
            ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
            worker.setName("My-ForkJoin-thread-" + worker.getPoolIndex());
            return worker;
        }
    };

    private static void testForkJoinSub(int parallelism, int arr[]) throws Exception {
        ForkJoinPool forkJoinPool = new ForkJoinPool(parallelism, factory, null, false);
        Instant now = Instant.now();
        RecursiveTask task = new CalcTask(arr, 0, arr.length);
        ForkJoinTask<Long> work = forkJoinPool.submit(task);
        Long retLong = work.get();
        System.out.println("forkJoin sum=" + retLong);
        System.out.println("forkJoin 耗时：" + Duration.between(now, Instant.now()).toMillis());
    }

    public static void main(String[] args) throws Exception {
        int len = 10000000;
        int arr[] = new int[len];
        for (int i = 0 ;i<len;i++)
            arr[i] = i;
        testForkJoinSub(8,arr);
    }
}
